document.addEventListener('DOMContentLoaded', function() {
    const baseURL = 'http://127.0.0.1:5000'; // 本地代理的Flask服务器
    const urlParams = new URLSearchParams(window.location.search);
    const playlistId = urlParams.get('playlist_id');

    if (!playlistId) {
        console.error('No playlist_id found in URL');
        return;
    }

    const playlistCover = document.getElementById('playlistCover');
    const playlistName = document.getElementById('playlistName');
    const playlistDesc = document.getElementById('playlistDesc');
    const songListElement = document.getElementById('songList');
    const musicPlayer = document.getElementById('music-player');
    const albumCover = document.getElementById('album-cover');
    const songNameElement = document.getElementById('song-name');
    const singerNameElement = document.getElementById('singer-name');
    const playButton = document.getElementById('play-button');
    const prevButton = document.getElementById('prev-button');
    const nextButton = document.getElementById('next-button');
    const progressBar = document.getElementById('progress-bar');
    const currentTimeElement = document.getElementById('current-time');
    const totalTimeElement = document.getElementById('total-time');
    const currentLyricElement = document.getElementById('current-lyric');
    const lyricsButton = document.getElementById('lyrics-button');
    const playModeButton = document.getElementById('play-mode');
    const lyricsModal = document.getElementById('lyrics-modal');
    const closeLyricsBtn = document.getElementById('close-lyrics');
    const lyricsContent = document.getElementById('lyrics-content');
    const volumeSlider = document.getElementById('volume-slider');

    let playlist = [];
    let currentSongIndex = 0;
    let audio = null;
    let isSeeking = false;
    let playMode = 'sequence'; // 'sequence', 'shuffle', 'repeat'
    let parsedLyrics = [];

    function fetchPlaylistDetails() {
        fetch(`${baseURL}/songlist?id=${playlistId}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    console.error(data.error);
                    return;
                }

                const playlistData = data.data;
                playlistCover.src = playlistData.logo || playlistData.dir_pic_url2;
                playlistName.textContent = playlistData.dissname;
                playlistDesc.textContent = playlistData.desc;

                const songs = playlistData.songlist;
                displaySongs(songs);
                playlist = songs; // 保存播放列表
            })
            .catch(error => console.error('Error fetching playlist details:', error));
    }

    function displaySongs(songs) {
        songListElement.innerHTML = '';

        songs.forEach((song, index) => {
            const songItem = document.createElement('li');
            songItem.classList.add('song-item');
            const songName = song.songname;
            const singerName = song.singer.map(s => s.name).join(', '); // 获取所有歌手名称
            const albumName = song.albumname;
            const songMid = song.songmid; // 歌曲的MID
            const duration = formatTime(song.interval);

            songItem.innerHTML = `
                <div class="song-title">${songName}</div>
                <div class="song-artist">${singerName}</div>
                <div class="song-album">${albumName}</div>
                <div class="song-duration">${duration}</div>
                <button class="play-button" data-index="${index}">播放</button>
            `;

            songItem.querySelector('.play-button').addEventListener('click', function() {
                currentSongIndex = index;
                playCurrentSong();
            });

            songListElement.appendChild(songItem);
        });
    }

    function formatTime(seconds) {
        const minutes = Math.floor(seconds / 60);
        const remainingSeconds = seconds % 60;
        return `${minutes}:${remainingSeconds < 10 ? '0' : ''}${remainingSeconds}`;
    }

    function playCurrentSong() {
    const song = playlist[currentSongIndex];
    const songMid = song.songmid;

    const songName = song.songname;
    const singerName = song.singer.map(s => s.name).join(', ');
    const albumCover = `http://y.gtimg.cn/music/photo_new/T002R300x300M000${song.albummid}.jpg`;

    fetch(`${baseURL}/user/refresh`, { method: 'GET', credentials: 'include' })
        .then(() => fetchPlayUrl(songMid))
        .then(songUrl => {
            if (songUrl) {
                updatePlayer(songUrl, songName, singerName, albumCover);
                playSong(songUrl);
                fetchLyrics(songMid)
                    .then(lyrics => {
                        parsedLyrics = parseLyrics(lyrics);
                    })
                    .catch(error => console.error('Error fetching lyrics:', error));
            } else {
                console.error('无法获取播放链接');
            }
        })
        .catch(error => console.error('Error:', error));
}



    function fetchPlayUrl(songMid) {
    return fetch(`${baseURL}/song/url?id=${songMid}`, {
        method: 'GET',
        credentials: 'include'
    })
    .then(response => {
        if (!response.ok) {
            throw new Error(`HTTP error! status: ${response.status}`);
        }
        return response.json();
    })
    .then(data => {
        if (data.result !== 100) {
            throw new Error('API response error: ' + data.result);
        }
        return data.data;  // 假设播放链接在 data.data 中
    })
    .catch(error => {
        console.error('Error fetching play URL:', error);
        return null; // 返回 null 表示无法获取播放链接
    });
}


    function playSong(url) {
        if (audio) {
            audio.pause();
        }
        audio = new Audio(url);
        audio.play()
            .then(() => {
                musicPlayer.style.display = 'flex';
                setTimeout(() => {
                    musicPlayer.style.opacity = 1;
                }, 10);
                playButton.textContent = '⏸️';
                updateProgressBar();
                updateCurrentLyric();

                audio.addEventListener('ended', function() {
                    if (playMode === 'repeat') {
                        playCurrentSong();
                    } else {
                        nextButton.click();
                    }
                });
            })
            .catch(error => console.error('Error playing song:', error));
    }

    function updatePlayer(url, songName, singerName, albumCoverUrl) {
        albumCover.src = albumCoverUrl;
        songNameElement.textContent = songName;
        singerNameElement.textContent = singerName;
        musicPlayer.style.display = 'flex';
        setTimeout(() => {
            musicPlayer.style.opacity = 1;
        }, 10);
    }

    function fetchLyrics(songMid) {
        return fetch(`${baseURL}/lyric?songmid=${songMid}`)
            .then(response => response.json())
            .then(data => {
                if (data.error) {
                    throw new Error(data.error);
                }
                return data.data.lyric;
            });
    }

    function showLyrics(lyrics) {
        lyricsContent.innerHTML = lyrics.replace(/\n/g, '<br>');
        lyricsModal.style.display = 'block';
    }

    function updateCurrentLyric() {
        if (!parsedLyrics || parsedLyrics.length === 0) return;

        let currentLyric = '';
        const currentTime = Math.floor(audio.currentTime);

        for (let i = 0; i < parsedLyrics.length; i++) {
            if (currentTime >= parsedLyrics[i].time) {
                currentLyric = parsedLyrics[i].text;
            } else {
                break;
            }
        }

        if (currentLyric !== currentLyricElement.textContent) {
            currentLyricElement.style.opacity = 0;
            setTimeout(() => {
                currentLyricElement.textContent = currentLyric;
                currentLyricElement.style.opacity = 1;
            }, 500); // 渐变时间
        }
    }

   function updateProgressBar() {
    if (audio && !isSeeking) {
        progressBar.max = Math.floor(audio.duration); // 取整
        progressBar.value = Math.floor(audio.currentTime); // 取整
        currentTimeElement.textContent = formatTime(Math.floor(audio.currentTime));
        totalTimeElement.textContent = formatTime(Math.floor(audio.duration));

        // 更新当前歌词
        updateCurrentLyric(Math.floor(audio.currentTime));
    }
    requestAnimationFrame(updateProgressBar);
}

    progressBar.addEventListener('input', function() {
    isSeeking = true;
    currentTimeElement.textContent = formatTime(Math.floor(progressBar.value));
});

progressBar.addEventListener('change', function() {
    isSeeking = false;
    if (audio) {
        audio.currentTime = Math.floor(progressBar.value); // 取整
    }
});

    playButton.addEventListener('click', function() {
        if (audio) {
            if (audio.paused) {
                audio.play();
                playButton.textContent = '⏸️';
                musicPlayer.style.opacity = 1;
            } else {
                audio.pause();
                playButton.textContent = '▶️';
                musicPlayer.style.opacity = 1; // 保持播放器显示
            }
        }
    });

    prevButton.addEventListener('click', function() {
        if (playMode === 'shuffle') {
            currentSongIndex = Math.floor(Math.random() * playlist.length);
        } else {
            currentSongIndex = (currentSongIndex - 1 + playlist.length) % playlist.length;
        }
        playCurrentSong();
    });

        nextButton.addEventListener('click', function() {
        if (playMode === 'shuffle') {
            currentSongIndex = Math.floor(Math.random() * playlist.length);
        } else if (playMode === 'repeat') {
            // No need to change currentSongIndex, just replay the current song
        } else {
            currentSongIndex = (currentSongIndex + 1) % playlist.length;
        }
        playCurrentSong();
    });

    lyricsButton.addEventListener('click', function() {
        if (parsedLyrics.length > 0) {
            showLyrics(parsedLyrics.map(lyric => lyric.text).join('\n'));
        }
    });

    closeLyricsBtn.addEventListener('click', function() {
        lyricsModal.style.display = 'none';
    });

    playModeButton.addEventListener('click', function() {
        if (playMode === 'sequence') {
            playMode = 'shuffle';
            playModeButton.textContent = '🔀';
        } else if (playMode === 'shuffle') {
            playMode = 'repeat';
            playModeButton.textContent = '🔂';
        } else {
            playMode = 'sequence';
            playModeButton.textContent = '🔁';
        }
    });

    volumeSlider.addEventListener('input', function() {
        if (audio) {
            audio.volume = volumeSlider.value;
        }
    });

    window.addEventListener('click', function(event) {
        if (event.target === lyricsModal) {
            lyricsModal.style.display = 'none';
        }
    });

    function parseLyrics(lyrics) {
        const lines = lyrics.split('\n');
        const parsedLyrics = [];
        lines.forEach(line => {
            const match = line.match(/\[(\d+):(\d+\.\d+)\](.*)/);
            if (match) {
                const time = parseInt(match[1]) * 60 + parseFloat(match[2]);
                const text = match[3];
                parsedLyrics.push({ time, text });
            }
        });
        return parsedLyrics;
    }

    fetchPlaylistDetails();
});



